package com.link.base.base.saleactivity.service;

import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.coupons.dao.mybatis.mapper.BrandSeriesMapper;
import com.link.base.base.coupons.dao.mybatis.mapper.CouponsMapper;
import com.link.base.base.coupons.dao.mybatis.mapper.ProCouponsMapper;
import com.link.base.base.coupons.model.BrandSeries;
import com.link.base.base.coupons.model.CollectRecord;
import com.link.base.base.coupons.model.Coupons;
import com.link.base.base.coupons.model.ProCoupons;
import com.link.base.base.coupons.service.CollectRecordService;
import com.link.base.base.member.util.MpPayConstants;
import com.link.base.base.member.util.MpPayTools;
import com.link.base.base.order.model.SaleOrder;
import com.link.base.base.order.service.SaleOrderService;
import com.link.base.base.saleactivity.dao.mybatis.mapper.*;
import com.link.base.base.saleactivity.model.*;
import com.link.base.base.user.model.User;
import com.link.base.base.user.service.UserService;
import com.link.base.base.wechat.service.ArticlesService;
import com.link.base.core.basic.util.YmlConstants;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.interceptor.SecurityInterceptor;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: wangdawei
 * @date: 2018/6/1
 * 营销活动-serviceImp
 */

@Service
public class SaleActivityServiceImpl extends BasicServiceImpl<SaleActivity> implements SaleActivityService {
    private static final int UNLIMITED_REFFLETIMES = 999999;
    private static final Double TOTAL_SUMWEIGHT = 100.0;
    private static final String strN = "N";

    @Resource
    private SaleActivityMapper saleActivityMapper;

    @Resource
    private RaffleDetailService raffleDetailService;

    @Resource
    private OddsService oddsService;
    @Resource
    private SaleOrderService saleOrderService;

    @Resource
    private SalActStoreMapper salActStoreMapper;

    @Resource
    private SalActOrgMapper salActOrgMapper;

    @Resource
    private CouponsMapper couponsMapper;

    @Resource
    private BrandSeriesMapper brandSeriesMapper;

    @Resource
    private ProCouponsMapper proCouponsMapper;

    @Resource
    private ArticlesService articlesService;

    @Resource
    private OddsMapper oddsMapper;

    @Resource
    private AccountService accountService;

    @Resource
    private CollectRecordService collectRecordService;

    @Resource
    private UserService userService;

    @Resource
    private AccntCampMonitorService accntCampMonitorService;

    @Resource
    private AccntCampMonitorMapper accntCampMonitorMapper;


    @Override
    public BasicMapper<SaleActivity> getBasicMapper() {
        return saleActivityMapper;
    }

    /**
     * <p>筛选门店商数据</p>
     * <p>Description</p>
     * @author wangdawei
     * @date 2018/6/10
     */
    @Override
    public List<SaleActivity> queryStoreAcntByExamplePage(SaleActivity entity) throws Exception {
        return saleActivityMapper.queryStoreAcntByExamplePage(entity);
    }

    /**
     * <p>筛选渠道商数据</p>
     * <p>Description</p>
     * @author wangdawei
     * @date 2018/6/10
     */
    @Override
    public List<SaleActivity> queryCeStoreAcntByExamplePage(SaleActivity entity) throws Exception {
        return saleActivityMapper.queryCeStoreAcntByExamplePage(entity);
    }

    /**
     * @Author: wangdawei
     * @param act
     * @Date: 2018/6/1
     * @Description: Object[] arry
     * arry【0】 返回大转盘剩余抽奖次数，arry【1】 返回组合字符串，用于判断提示客户不能抽奖原因
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public Object[] querybigWheelInfoByAtyIdAndAcctId(SaleActivity act, QueryParams qps, HttpServletRequest request) throws Exception {
        Account entity = new Account();
        Object[] arry = new Object[5];
        //日抽奖次数
        int times = 0;
        //总抽奖次数
        int times1 = 0;
        //剩余抽奖次数
        int restTime = 0;
        //较小抽奖次数
        int smallTime = 0;
        String str1 = "";
        String str2 = "";
        //电话号码存在查询客户表
        if (StringUtils.isNotBlank(act.getPhoneNum())) {
            entity.setMobilePhone1(act.getPhoneNum());
            entity.setAcctChannel("Campaign");
            entity.setPageFlag(false);
            entity.setCorpid(act.getCorpid());
            entity.setLoginCorpId(act.getCorpid());
        }
        List<Account> acctList = accountService.queryByExamplePage(entity);
        Account account = new Account();
        Long accntId = 0L;
        //是否存在活动客户
        for (int i = 0; acctList != null && i < acctList.size(); i++) {
            if (StringUtils.isNotBlank(acctList.get(i).getAcctType())
                    && "Campaign".equals(acctList.get(i).getAcctChannel())) {
                account = acctList.get(i);
                accntId = acctList.get(i).getId();
                break;
            }
        }
        //活动客户不存在，创建活动客户
        if (acctList.size() == 0)
        {
            //客户不存在则创建客户
            account.setMobilePhone1(act.getPhoneNum());
            account.setAcctType("ChannelConsumer");
            account.setAcctChannel("Campaign");
            account.setAcctStatus("Y");
            account.setAcctLevel("A");
            account.setIsOldCustomer("N");
            account.setAcctStage("PotentialConsumer");
            account.setCorpid(act.getCorpid());
            account.setLoginCorpId(act.getCorpid());
            account.setAcctName("活动客户" + act.getPhoneNum().substring(7, 11));
            Long id = keyGenerateService.keyGenerate();
            account.setPostnId(0L);
            account.setId(id);
            accountService.insert(account);
            accntId = id;
        }
        SaleOrder saleOrder = new SaleOrder();
        RaffleDetail raffleDetail = new RaffleDetail();
        raffleDetail.setActivityId( act.getId());
        raffleDetail.setAccntId(accntId);
        raffleDetail.setCorpid(act.getCorpid());
        raffleDetail.setLoginCorpId(act.getCorpid());
        //查看总抽奖次数
        List<RaffleDetail> timeList = raffleDetailService.queryByExamplePage(raffleDetail);
        raffleDetail.setRaffleTime(DateUtil.dateToStr(new Date(),"yyyy-MM-dd"));
        //查看日抽奖次数
        List<RaffleDetail> dayTimeList = raffleDetailService.queryByExamplePage(raffleDetail);
        int dayUserTimes = dayTimeList.size();
        switch (act.getTotaltmLimitType()) {
            default:
                break;
            //消费者总抽奖次数无限制
            case ("NoLimit"):
                times = UNLIMITED_REFFLETIMES;
                str1 = "A";
                break;
            //消费者总抽奖次数有限制，限制由客户手动输入
            case ("NumberLimited"):
                times = act.getWinTime();
                str1 = "B";
                break;
            //消费者总抽奖次数有限制，限制依据客户成单次数
            case ("OrderLimited "):
                saleOrder.setAcctId(accntId);
                saleOrder.setCorpid(act.getCorpid());
                saleOrder.setLoginCorpId(act.getCorpid());
                times = saleOrderService.selectCountByacctId(saleOrder);
                str1 = "C";
                break;
            //消费者总抽奖次数有限制，限制依据客户满一定金额成单次数。
            case ("EligibleOrderLimited"):
                saleOrder.setAcctId(accntId);
                saleOrder.setLoginCorpId(act.getCorpid());
                saleOrder.setCorpid(act.getCorpid());
                //成单金额限制
                saleOrder.setOrderTotalAmount((double) act.getWinAmt());
                times = saleOrderService.selectCountByacctId(saleOrder);
                str1 = "D";
                break;
        }

        switch (act.getDaytmLimitType()) {
            default:
                break;
            //消费者日抽奖次数无限制
            case ("NoLimit"):
                times1 = UNLIMITED_REFFLETIMES;
                str2 = "E";
                break;
            //消费者日抽奖次数有限制，限制由客户手动输入
            case ("NumberLimited"):
                times1 = act.getDaywinTime();
                str2 = "F";
                break;
            //消费者日抽奖次数有限制，限制依据客户成单次数。
            case ("OrderLimited"):
                saleOrder.setAcctId(accntId);
                saleOrder.setLoginCorpId(act.getCorpid());
                saleOrder.setCorpid(act.getCorpid());
                times1 = saleOrderService.selectCountByacctId(saleOrder);
                str2 = "G";
                break;
            //消费者日抽奖次数有限制，限制依据客户满一定金额成单次数。
            case ("EligibleOrderLimited"):
                saleOrder.setAcctId(accntId);
                saleOrder.setLoginCorpId(act.getCorpid());
                saleOrder.setCorpid(act.getCorpid());
                //日成单金额限制
                saleOrder.setOrderTotalAmount((double) act.getDaywinAmt());
                times1 = saleOrderService.selectCountByacctId(saleOrder);
                str2 = "H";
                break;
        }
        // 总使用次数
        int userTimes = timeList.size();
        //计算消费者剩余抽奖次数
        if (times - userTimes > 0) {
            smallTime = times >= times1 ? times1 : times;
            restTime = smallTime - dayUserTimes >= times - userTimes ? times - userTimes : smallTime - dayUserTimes;
            //一句str 给客户不同的提示语
            String str = str1 + str2;
            arry[0] = restTime - 1 ;
            //剩余抽奖次数
            arry[1] = str;
        } else {
            arry[0] = 0;
            arry[1] = "BE";
        }
        arry[2]  = accntId;
        arry[3] = timeList.size();
        arry[4] = dayTimeList.size();
        return arry;
    }

    /**
     * 根据Math.random()产生一个double型的随机数，判断每个奖品出现的概率
     * @author wangdawei
     * @param prizes
     * @return random：奖品列表prizes中的序列（prizes中的第random个就是抽中的奖品）
     */
    public int getPrizeIndex(List<Odds> prizes) {
        int random = -1;
        try {
            //计算总权重
            double sumWeight = 0;
            for (Odds p : prizes) {
                sumWeight += p.getOdds();
            }
            //产生随机数
            double randomNumber;
            randomNumber = Math.random();
            //根据随机数在所有奖品分布的区域并确定所抽奖品
            double d1 = 0;
            double d2 = 0;
            if (sumWeight != 0) {
                for (int i = 0; i < prizes.size(); i++) {
                    d2 += Double.parseDouble(String.valueOf(prizes.get(i).getOdds())) / sumWeight;
                    if (i == 0) {
                        d1 = 0;
                    } else {
                        d1 += Double.parseDouble(String.valueOf(prizes.get(i - 1).getOdds())) / sumWeight;
                    }
                    if (randomNumber >= d1 && randomNumber <= d2) {
                        random = i;
                        break;
                    }
                }
            } else {
                throw new ServiceException("SALEACTIVITY-001");
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            System.out.println("生成抽奖随机数出错，出错原因：" + e.getMessage());
        }
        return random;
    }

    /**
     * @author wangdawei
     * @param odd  概率对象
     * @param act  活动对象
     * @param accntId  客户id
     * @param arry  数组
     * @return Odds 返回抽奖信息
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public Odds reffle(Odds odd, Object[] arry, SaleActivity act, Long accntId) throws Exception {
        //由于抽奖用户处于未登录状态手动添加一个系统默认用户
        User user = userService.queryUserByCropId(act.getCorpid());
        SecurityInterceptor.tempUser.set(user);
        //记录中奖次数
        Odds result = new Odds();
        String str = (String) arry[1];
        odd.setPageFlag(false);
        odd.setCorpid(act.getCorpid());
        odd.setLoginCorpId(act.getCorpid());
        List<Odds> list = oddsService.queryByExamplePage(odd);
        odd.setOnlyCountFlag(true);
        //区分虚拟奖品与真实奖品
        Double sumWeight = TOTAL_SUMWEIGHT;
        Double ralWeight = 0.0;
        Double virWeight = 0.0;
        //存放真实奖品
        List<Odds> listoddNew = new ArrayList<Odds>();
        List<Integer> listindex = new ArrayList<Integer>();
        for (int i = 0; i < list.size(); i++) {
            if (!"Virtual".equals(list.get(i).getCouponsClass())) {
                listoddNew.add(list.get(i));
                ralWeight += list.get(i).getOdds();
            } else {
                listindex.add(i);
            }
        }

        //添加虚拟奖品
        if (listindex.size() != 0) {
            virWeight = sumWeight - ralWeight;
            for (int i = 0; i < listindex.size(); i++) {
                if (listindex.size() == 3 || listindex.size() == 6) {
                    BigDecimal bg = BigDecimal.valueOf(virWeight / listindex.size());
                    double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    list.get(listindex.get(i)).setOdds(f1);
                } else {
                    list.get(listindex.get(i)).setOdds(virWeight / listindex.size());
                }
                listoddNew.add(list.get(listindex.get(i)));
            }
        }
        try {
            //判断活动是否过期，以及对抽奖次数的限定
            if ((int) arry[0] >= 0) {
                RaffleDetail reffle = new RaffleDetail();
                int index = getPrizeIndex(listoddNew);
                String virtual = "Virtual";
                if (!virtual.equals(listoddNew.get(index).getCouponsClass())) {
                    reffle.setWinOrnot("Y");
                    result = listoddNew.get(index);
                    //客户已中奖，判断奖品是否达到客户可领取上限
                    Odds odds = listoddNew.get(index);
                    CollectRecord record = new CollectRecord();
                    record.setAccntId(accntId);
                    record.setCouponsId(odds.getCouponsId());
                    record.setOnlyCountFlag(true);
                    record.setPageFlag(false);
                    //中奖提示弹框
                    result.setPromptClass("Win");
                    Coupons c = new Coupons();
                    c.setId(odds.getCouponsId());
                    c.setLoginCorpId(act.getCorpid());
                    c.setCorpid(act.getCorpid());
                    Coupons couponss = couponsMapper.queryById(c);
                    record.setLoginCorpId(act.getCorpid());
                    record.setCorpid(act.getCorpid());
                    List<CollectRecord> collectRecord = collectRecordService.queryByExamplePage(record);
                    if (collectRecord != null && couponss.getLimitGet() != null) {
                        if (collectRecord.get(0).getTotal() > couponss.getLimitGet()) {
                            result.setCanGet("N");
                            //中奖提示弹框（已中奖但超过可领取上限）
                            result.setPrompt("超过奖品可领取上限，该奖品不能领取");
                        } else {
                            result.setCanGet("Y");
                        }
                    } else {
                        result.setCanGet("Y");
                    }
                } else {
                    result = listoddNew.get(index);
                    reffle.setWinOrnot("N");
                    //未中奖提示弹框
                    result.setPromptClass("NoPrize");
                    result.setCouponsName("谢谢惠顾");
                    result.setPrompt(act.getUnwinPrompt());
                }
                if (StringUtils.isNotBlank(result.getCouponsClass())) {
                    reffle.setCouponsClass(result.getCouponsClass());
                }
                if (StringUtils.isNotBlank(result.getCanGet())) {
                    reffle.setCanGet(result.getCanGet());
                }
                reffle.setActivityId(result.getActivityId());
                reffle.setAccntId(accntId);
                reffle.setRaffleTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
                reffle.setCorpid(act.getCorpid());
                Long reffleId = keyGenerateService.keyGenerate();
                reffle.setId(reffleId);
                raffleDetailService.insert(reffle);
                result.setReffleId(reffleId);
            } else {
                result.setLocation(-1);
                //次数不足弹框
                result.setPromptClass("InsufficientNumber");
                //定义组合字母
                String af = "AF";
                String bf = "BF";
                String ag = "AG";
                String de = "DE";
                String ch = "CH";
                String cg = "CG";
                String dg = "DG";
                String dh = "DH";
                String bg = "BG";
                String ah = "AH";
                String be = "BE";
                String ce = "CE";
                String cf = "CF";
                String df = "DF";
                String bh = "BH";
                if (af.equals(str) || bf.equals(str)) {
                    //超过日次数限制提示
                    result.setPrompt(act.getDtlLmtPrompt());
                } else if (ag.equals(str) || ch.equals(str) || cg.equals(str)
                        || de.equals(str) || dg.equals(str) || dh.equals(str) || bg.equals(str) || ah.equals(str)) {
                    //超过成单次数限制
                    result.setPrompt(act.getTlLmtPrompt());
                } else if (be.equals(str) || ce.equals(str)) {
                    //超过总数限制提示
                    result.setPrompt(act.getLmtPromt());
                } else if (cf.equals(str) || df.equals(str) || bf.equals(str) || bh.equals(str)) {
                    //存在情况说明：日抽奖次数未按日成单次数限制，而总成单次数为管理员手动输入的。
                    if (act.getDaywinTime() > act.getWinTime()) {
                        //超过成单次数限制提示
                        result.setPrompt(act.getTlLmtPrompt());
                    }
                    //超过日次数限制提示
                    result.setPrompt(act.getDtlLmtPrompt());
                }
            }
        } catch (Exception ex) {
            LCLogger.withException(ex);
        }
        return result;
    }

    /**
     * @author wangdawei
     * @param entity
     * 保存营销活动
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void insertSaleActivity(SaleActivity entity) throws Exception {
        //保存活动信息,创建活动Id
        CoreUser user = UserUtil.getUser();
        String couponCamp = "CouponCamp";
        String wheelCamp =  "WheelCamp";
        //获取系统参数中默认维护的相关图片信息
        if (null == entity.getAtyPicBackId()) {
            if (couponCamp.equals(entity.getActivityType())) {
                entity.setAtyPicBackId(Long.parseLong(PropertyUtil.getProperty("couponCampBackPicId", user.getCorpid())));
            } else if (wheelCamp.equals(entity.getActivityType())) {
                entity.setAtyPicBackId(Long.parseLong(PropertyUtil.getProperty("bigWheelCampBackPicId", user.getCorpid())));
            }
        }

        if (null == entity.getMicselID() && wheelCamp.equals(entity.getActivityType())) {
            //存放一个默认的大转盘背景音乐
            entity.setMicselID(Long.parseLong(PropertyUtil.getProperty("bigWheelCampBackMusicId", user.getCorpid())));
        }
        entity.setOrgId(UserUtil.getUser().getOrgId());
        entity.setPostnId(UserUtil.getUser().getPostnId());
        if (entity.getAccntStageArry() != null && entity.getAccntStageArry().length > 0) {
            System.out.println(entity.getAccntStageArry());
            entity.setAccntStage(StringUtils.getStr(entity.getAccntStageArry(), ","));
        }

        if (entity.getStoreLevelArry() != null && entity.getStoreLevelArry().length > 0) {
            entity.setStoreLevel(StringUtils.getStr(entity.getStoreLevelArry(), ","));
        }

        if (entity.getStoreTypeArry() != null && entity.getStoreTypeArry().length > 0) {
            entity.setStoreType(StringUtils.getStr(entity.getStoreTypeArry(), ","));
        }
        Long activityId = entity.getId();
        if (null == activityId) {
            activityId = keyGenerateService.keyGenerate();
            entity.setId(activityId);
        }
        /***************生成活动二维码图片并保存********************/

        //区分活动类型，不同活动类型有不同的二维码链接
        String strJson = "";
        if (couponCamp.equals(entity.getActivityType())) {
            //二维码内容,跳转到优惠卷活动H5
            strJson = PropertyUtil.getProperty("marketCampMobileCouponPageURL",
                    user.getCorpid()) + "?id=" + activityId + "&&corpid=" + user.getCorpid();
        } else {
            //二维码内容,跳转到大转盘活动H5
            strJson = PropertyUtil.getProperty("marketCampMobilePageURL", user.getCorpid()) + "?id=" + activityId + "&&corpid=" + user.getCorpid();
        }
        //二维码存放位置,静态路径。
        String file = "/web/file/saleactivity/" + user.getCorpid() + "/";
        String fileName = activityId + "_" + DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss") + ".png";
        //二维码的本地路径（默认Portal文件系统根目录）
        QRCodeUtil.tomakeMode(strJson, YmlConstants.getPortalShareFileDir() + file, fileName, 160, 160);
        entity.setCodeSavPath(file + fileName);
        entity.setCodeUrl(strJson);
        /***************生成活动二维码图片生成结束********************/
        // 保存活动
        saleActivityMapper.insert(entity);

        //保存活动下的适用门店
        List<SalActStore> salActStoreList = entity.getSalActStoreList();
        if (salActStoreList != null && salActStoreList.size() > 0) {
            for (int i = 0; i < salActStoreList.size(); i++) {
                SalActStore salActStore = salActStoreList.get(i);
                Long salActStoreId = salActStore.getId();
                if (null == salActStoreId) {
                    salActStoreId = keyGenerateService.keyGenerate();
                    salActStore.setId(salActStoreId);
                }
                salActStore.setActivityId(activityId);
                salActStoreMapper.insert(salActStore);
            }
        }

        //保存活动下的适用区域
        List<SalActOrg> salActOrgList = entity.getSalActOrgList();
        if (salActOrgList != null && salActOrgList.size() > 0) {
            for (int i = 0; i < salActOrgList.size(); i++) {
                SalActOrg salActOrg = salActOrgList.get(i);
                Long salActOrgId = salActOrg.getId();
                if (null == salActOrgId) {
                    salActOrgId = keyGenerateService.keyGenerate();
                    salActOrg.setId(salActOrgId);
                }
                salActOrg.setActivityId(activityId);
                salActOrgMapper.insert(salActOrg);
            }
        }

        //保存大转盘活动下的抽奖规则
        List<Odds> oddsList = entity.getOddList();
        if (oddsList != null && oddsList.size() > 0) {
            for (int j = 0; j < oddsList.size(); j++) {
                Odds odds = oddsList.get(j);
                Long oddsId = odds.getId();
                if (null == oddsId) {
                    oddsId = keyGenerateService.keyGenerate();
                    odds.setId(oddsId);
                    //特殊处理，主要是区分实物奖品，优惠券，虚拟奖品
                    String couponsIdClass = oddsList.get(j).getCoupIdClass();
                    String[] arry = couponsIdClass.split(",");
                    if (StringUtils.isNotBlank(arry[0])) {
                        odds.setCouponsId(Long.parseLong(arry[0]));
                    }
                    if (StringUtils.isNotBlank(arry[1])) {
                        odds.setCouponsClass(arry[1]);
                    }
                    odds.setOdds(oddsList.get(j).getOdds());
                    odds.setLocation(oddsList.get(j).getLocation());
                    odds.setActivityId(activityId);
                    oddsMapper.insert(odds);
                }
            }
        }

        //保存活动下的奖品（奖品下的适用门店信息默认继承活动）
        List<Coupons> couponsList = entity.getCouponsList();
        if (couponsList != null && couponsList.size() > 0) {
            for (int i = 0; i < couponsList.size(); i++) {
                Coupons coupons = couponsList.get(i);
                coupons.setOrgId(UserUtil.getUser().getOrgId());
                coupons.setPostnId(UserUtil.getUser().getPostnId());
                Long couponsId = coupons.getId();
                if (null == couponsId) {
                    couponsId = keyGenerateService.keyGenerate();
                    coupons.setId(couponsId);
                }
                if (StringUtils.isNotBlank(coupons.getCouponsClass()) && "Coupon".equals(coupons.getCouponsClass())) {
                    String str = PropertyUtil.getProperty("couponGetDirectlyURL",
                            user.getCorpid()) + "?id=" + couponsId + "&&corpid=" + user.getCorpid();
                    //二维码存放位置,静态路径。
                    String coupfile = "/web/file/saleactivity/" + user.getCorpid() + "/";
                    String name = couponsId + "_" + DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss") + ".png";
                    //二维码的本地路径（默认Portal文件系统根目录）
                    QRCodeUtil.tomakeMode(str, YmlConstants.getPortalShareFileDir() + coupfile, name, 160, 160);
                    coupons.setCodeSavPath(coupfile + name);
                    coupons.setCodeUrl(str);
                }
                //领取数量默认为0
                coupons.setReceivedNum(0);
                coupons.setActivityId(activityId);
                if ("CouponCamp".equals(coupons.getCouponsType())) {
                    coupons.setBackPicId(entity.getAtyPicBackId());
                }
                couponsMapper.insert(coupons);
                //保存活动下的具体适用产品信息
                List<ProCoupons> proCouponsList = couponsList.get(i).getProCouponsList();
                if (proCouponsList != null && proCouponsList.size() > 0) {
                    for (int j = 0; j < proCouponsList.size(); j++) {
                        ProCoupons proCoupons = proCouponsList.get(j);
                        Long proCouponsId = proCoupons.getId();
                        if (null == proCouponsId) {
                            proCouponsId = keyGenerateService.keyGenerate();
                            proCoupons.setId(proCouponsId);
                        }
                        proCoupons.setCouponsId(couponsId);
                        proCouponsMapper.insert(proCoupons);
                    }
                }

                //保存活动下的品牌系列信息
                List<BrandSeries> brandSeriesbList = couponsList.get(i).getBrandSeriesList();
                if (brandSeriesbList != null && brandSeriesbList.size() > 0) {
                    for (int j = 0; j < brandSeriesbList.size(); j++) {
                        BrandSeries brandSeries = brandSeriesbList.get(j);
                        Long brandSeriesId = brandSeries.getId();
                        if (null == brandSeriesId) {
                            brandSeriesId = keyGenerateService.keyGenerate();
                            brandSeries.setId(brandSeriesId);
                        }
                        brandSeries.setCouponsId(couponsId);
                        if (StringUtils.isNotBlank(brandSeries.getBrandseriesType())) {
                            brandSeriesMapper.insert(brandSeries);
                        }
                    }
                }

                //优惠券同步到微信
                if (StringUtils.isNotBlank(coupons.getIsSyn())) {
                    if ("Y".equals(coupons.getIsSyn())) {
                        Map<String, Object> map = articlesService.createWxCard(coupons);
                        Object cardId = map.get("card_id");
                        // card_id存在表示卡券同步微信成功
                        if (cardId != null && StringUtils.isNotBlank(cardId.toString()))
                        {
                            coupons.setWeChatCouponId(cardId.toString());
                            coupons.setSynState("Succeeded");
                            coupons.setSynTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
                            couponsMapper.update(coupons);
                        } else {
                            //同步失败，数据回滚。
                            // 事物回滚
                            throw new ServiceException("SALEACTIVITY-002");
                        }
                    }
                }
            }
        }
    }

    /**
     * @author wangdawei
     * @param entity
     * 活动编辑通过id查询活动信息，用于回显数据
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public SaleActivity getSaleActivityById(SaleActivity entity) throws Exception {
        if (null == entity.getId()) {
            throw new ServiceException("SALEACTIVITY-003");
        }
        SaleActivity saleActivity = saleActivityMapper.queryById(entity);
        if (saleActivity == null) {
            return null;
        }
        if (StringUtils.isNotBlank(saleActivity.getAccntStage())) {
            String[] arry = saleActivity.getAccntStage().split(",");
            saleActivity.setAccntStageArry(arry);
        }
        if (StringUtils.isNotBlank(saleActivity.getStoreLevel())) {
            String[] arry = saleActivity.getStoreLevel().split(",");
            saleActivity.setStoreLevelArry(arry);
        }
        if (StringUtils.isNotBlank(saleActivity.getStoreType())) {
            String[] arry = saleActivity.getStoreType().split(",");
            saleActivity.setStoreTypeArry(arry);
        }
        Long activityId = saleActivity.getId();
        //活动下的区域
        SalActOrg salActOrg = new SalActOrg();
        salActOrg.setActivityId(activityId);
        salActOrg.setPageFlag(false);
        List<SalActOrg> salActOrgList = salActOrgMapper.queryByExamplePage(salActOrg);
        saleActivity.setSalActOrgList(salActOrgList);

        //活动下的具体门店
        SalActStore salActStore = new SalActStore();
        salActStore.setActivityId(activityId);
        salActStore.setPageFlag(false);
        List<SalActStore> salActStoreList = salActStoreMapper.queryByExamplePage(salActStore);
        saleActivity.setSalActStoreList(salActStoreList);

        //活动下的优惠券
        Coupons coupons = new Coupons();
        coupons.setActivityId(activityId);
        coupons.setPageFlag(false);
        List<Coupons> couponsList = couponsMapper.queryByExamplePage(coupons);
        for (Coupons coupons1 : couponsList) {
            BrandSeries brandSeries = new BrandSeries();
            brandSeries.setCouponsId(coupons1.getId());
            List<BrandSeries> brandSeriesList = brandSeriesMapper.queryAll(brandSeries);
            coupons1.setBrandSeriesList(brandSeriesList);

            ProCoupons proCoupons = new ProCoupons();
            proCoupons.setCouponsId(coupons1.getId());
            List<ProCoupons> proCouponsList = proCouponsMapper.queryAll(proCoupons);
            coupons1.setProCouponsList(proCouponsList);
        }
        saleActivity.setCouponsList(couponsList);

//      活动下的奖品规则
        Odds odds = new Odds();
        odds.setActivityId(activityId);
        odds.setPageFlag(false);
        List<Odds> oddsList = oddsMapper.queryByExamplePage(odds);
        for (int i = 0; oddsList != null && i < oddsList.size(); i++) {
            if (StringUtils.isBlank(oddsList.get(i).getCouponsName()) && "Virtual".equals(oddsList.get(i).getCouponsClass())) {
                oddsList.get(i).setCouponsName("谢谢惠顾");
            }
        }
        saleActivity.setOddList(oddsList);
        return saleActivity;
    }


    /**
     * <p>营销活动编辑</p>
     * <p>Description</p>
     * @author wangdawei
     * @date 2018/6/10
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void updateSaleActivity(SaleActivity entity) throws Exception {

        Long activityId = entity.getId();
        if (null == activityId) {
            throw new ServiceException("SALEACTIVITY-003");
        }
        //查询旧的活动数据
        SaleActivity saleActivity = new SaleActivity();
        saleActivity.setId(activityId);
        saleActivity = this.getSaleActivityById(saleActivity);

        if (saleActivity == null) {
            throw new ServiceException("SALEACTIVITY-004");
        }
        if (StringUtils.isNotBlank(entity.getCodeSavPath())) {
            String codePath = entity.getCodeSavPath().split("/web/file/saleactivity/")[1];
            entity.setCodeSavPath("/web/file/saleactivity/" + codePath);
        }
        if (entity.getAccntStageArry() != null && entity.getAccntStageArry().length > 0) {
            entity.setAccntStage(StringUtils.getStr(entity.getAccntStageArry(), ","));
        } else {
            entity.setAccntStage(null);
        }

        if (entity.getStoreLevelArry() != null && entity.getStoreLevelArry().length > 0) {
            entity.setStoreLevel(StringUtils.getStr(entity.getStoreLevelArry(), ","));
        } else {
            entity.setStoreLevel(null);
        }

        if (entity.getStoreTypeArry() != null && entity.getStoreTypeArry().length > 0) {
            entity.setStoreType(StringUtils.getStr(entity.getStoreTypeArry(), ","));
        } else {
            entity.setStoreType(null);
        }
        //更新活动
        saleActivityMapper.update(entity);
        /*编辑活动下的区域，前端传入的信息*/
        List<SalActOrg> salActOrgList = entity.getSalActOrgList();
        //本来数据库的信息
        List<SalActOrg> oldsalActOrgList = saleActivity.getSalActOrgList();
        for (int i = 0; salActOrgList != null && i < salActOrgList.size(); i++) {
            SalActOrg salActOrg = salActOrgList.get(i);
            Long salActOrgId = salActOrg.getId();
            //新建数据
            if ("NEW".equals(salActOrg.getRow_status())) {
                if (null == salActOrgId) {
                    salActOrgId = keyGenerateService.keyGenerate();
                    salActOrg.setId(salActOrgId);
                }
                salActOrg.setActivityId(activityId);
                salActOrgMapper.insert(salActOrg);
                //更新数据
            } else if ("UPDATE".equals(salActOrg.getRow_status())) {
                if (null == salActOrgId) {
                    throw new ServiceException("SALEACTIVITY-005");
                }
                salActOrg.setActivityId(activityId);
                salActOrgMapper.update(salActOrg);
            }
        }
        //找出无用数据并删除
        for (int i = 0; oldsalActOrgList != null && salActOrgList != null && i < oldsalActOrgList.size(); i++) {
            SalActOrg oldSalActOrg = oldsalActOrgList.get(i);
            boolean delFlag = true;
            for (int j = 0; oldsalActOrgList != null && j < salActOrgList.size(); j++) {
                if (oldSalActOrg.getId().equals(salActOrgList.get(j).getId())) {
                    delFlag = false;
                    break;
                }
            }
            //删除客户活动
            if (delFlag) {
                salActOrgMapper.deleteById(oldSalActOrg);
            }
        }
        /*编辑活动下的适用门店，前端传入的信息*/
        List<SalActStore> salActStoreList = entity.getSalActStoreList();
        //本来数据库的信息
        List<SalActStore> oldsalActStoreList = saleActivity.getSalActStoreList();
        for (int i = 0; salActStoreList != null && i < salActStoreList.size(); i++) {
            SalActStore salActStore = salActStoreList.get(i);
            Long salActStoreId = salActStore.getId();
            //新建数据
            if ("NEW".equals(salActStore.getRow_status())) {
                if (null == salActStoreId) {
                    salActStoreId = keyGenerateService.keyGenerate();
                    salActStore.setId(salActStoreId);
                }
                salActStore.setActivityId(activityId);
                salActStoreMapper.insert(salActStore);
                //更新数据
            } else if ("UPDATE".equals(salActStore.getRow_status())) {
                if (null == salActStoreId) {
                    throw new ServiceException("SALEACTIVITY-006");
                }
                salActStore.setActivityId(salActStoreId);
                salActStoreMapper.update(salActStore);
            }
        }
        //找出无用数据并删除
        for (int i = 0; oldsalActStoreList != null && salActStoreList != null && i < oldsalActStoreList.size(); i++) {
            SalActStore oldSalActStore = oldsalActStoreList.get(i);
            boolean delFlag = true;
            for (int j = 0; oldsalActStoreList != null && j < salActStoreList.size(); j++) {
                if (oldSalActStore.getId().equals(salActStoreList.get(j).getId())) {
                    delFlag = false;
                    break;
                }
            }
            //删除客户活动
            if (delFlag) {
                salActStoreMapper.deleteById(oldSalActStore);
            }
        }
        /*编辑活动下的抽奖规则，抽奖规则只存在编辑，不存在添加和删除，直接用前端传入的数据覆盖数据库信息，前端传入的信息*/
        List<Odds> scpOddList = entity.getOddList();
        for (int i = 0; scpOddList != null && i < scpOddList.size(); i++) {
            Odds odds = scpOddList.get(i);
            String str = odds.getCoupIdClass();
            String[] arry = str.split(",");
            if (StringUtils.isNotBlank(arry[0])) {
                odds.setCouponsId(Long.parseLong(arry[0]));
            }
            if (StringUtils.isNotBlank(arry[1])) {
                odds.setCouponsClass(arry[1]);
            }
            if (null == odds.getId()) {
                throw new ServiceException("SALEACTIVITY-007");
            }
            oddsMapper.update(odds);
        }
    }

    /**
     * 分享领券活动-加载页面
     * @author  wangdawei
     * @param entity
     * @return
     * @throws Exception
     */
    @Override
    public SaleActivity shareCouponLoading(SaleActivity entity) throws Exception {
        if (entity != null && null != entity.getId()) {
            if ("InProgress".equals(entity.getActivityState())) {
                //活动展示正常样式
                entity.setIsExpire("N");
            } else {
                //活动展示过期样式
                entity.setIsExpire("Y");
            }
        } else {
            throw new ServiceException("SALEACTIVITY-003");
        }
        return entity;
    }

    /**
     * 分享领券活动-加载页面
     * @author  wangdawei
     * @param saleActivity
     * @return
     * @throws Exception
     */
    @Override
    public SaleActivity showCompainDetail(SaleActivity saleActivity) throws Exception {

        CoreUser user = UserUtil.getUser();
        SaleActivity entity = new SaleActivity();
        Long sourceAccntId = 0L;
        Long accntId = 0L;
        if (null != user) {
            accntId  = user.getAcctId();
        } else {
            throw new ServiceException("PUBLIC-060");
        }

        if (saleActivity != null ) {
            if ( null != saleActivity.getId()) {
                entity = saleActivityMapper.queryById(saleActivity);
                sourceAccntId = saleActivity.getSourceAccntId();
            }

            if (null == sourceAccntId) {
                entity.setSourceAccntId(sourceAccntId);
            }

            if (null != accntId) {
                entity.setAccntId(accntId);
            }
        } else {
            throw new ServiceException("SALEACTIVITY-008");
        }

        //根据活动id带出活动下的优惠卷
        Coupons coupons = new Coupons();
        coupons.setPageFlag(false);
        coupons.setIsEffect("Y");
        coupons.setCouponsClass("Coupon");
        coupons.setActivityId(entity.getId());
        coupons.setAccntId(entity.getAccntId());
        List<Coupons>  couponsList = couponsMapper.queryByExamplePage(coupons);
        entity.setCouponsList(couponsList);
        //活动当前用户id 判断当前用户是否领过优惠券
        CollectRecord  collectRecord = new CollectRecord();
        if (couponsList.size() > 0) {
            for (Coupons coup : couponsList) {
                Integer num = coup.getCouponsNum();
                collectRecord.setCouponsId(coup.getId());
                collectRecord.setPageFlag(false);
                List<CollectRecord> recordList = collectRecordService.queryByExamplePage(collectRecord);
                //数量是否到达上限 N 没达到，Y 到达
                if (num > recordList.size()) {
                    coup.setAttr2("N");
                } else {
                    coup.setAttr2("Y");
                }
            }
            //判断当前客户是否已经参加过当前活动
            this.isReceiveCard(entity);
        }
        String invitationCamp = "InvitationCamp";
        if (invitationCamp.equals(entity.getActivityType())) {
//            MemberCard memberCard = new MemberCard();
//            memberCard.setId(entity.getMemCardId());
//            memberCard = memberCardMapper.queryById(memberCard);
//            //会员卡库存
//            Integer quantity = memberCard.getQuantity();
//            //会员卡发放数量
//            Integer receivedNum = memberCard.getReceivedNum();
//            //如果库存大于发放的，就是N 没达到
//            if (quantity > receivedNum) {
//                entity.setAttr2("N");
//            } else {
//                entity.setAttr2("Y");
//            }
        }
        this.getCount(entity);
        return entity;
    }

    /**
     * 判断用户是否是会员
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> isMpmeber(SaleActivity saleActivity) throws Exception {
        Map<String, Object> result = new HashMap<>(4);
        Account account = new Account();
        account.setId(UserUtil.getUser().getId());
        account = accountService.queryById(account);
        saleActivity = saleActivityMapper.queryById(saleActivity);
        if (null == account) {
            throw new Exception("用户不存在");
        }
        return result;
    }

    /**
     * 查询已分享好友列表
     * @param accntCampMonitor
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> accountList(AccntCampMonitor accntCampMonitor) throws Exception {
        Map<String, Object> result = new HashMap<>(8);
        AccntCampMonitor campMonitor = new AccntCampMonitor();
        campMonitor.setSalAcctId(accntCampMonitor.getSalAcctId());
        campMonitor.setSourceAccntId(UserUtil.getUser().getId());
        campMonitor.setActionType("Click");
        List<AccntCampMonitor> monitorList = accntCampMonitorService.queryByExampleList(campMonitor);
        //查询 活动
        SaleActivity saleActivity = new SaleActivity();
        saleActivity.setId(accntCampMonitor.getSalAcctId());
        saleActivity = saleActivityMapper.queryById(saleActivity);
        List<AccntCampMonitor> alist = new ArrayList<>();
        //判断分享到的好友所处状态
        for (AccntCampMonitor aCMonitor : monitorList) {
            aCMonitor.setSalAcctId(accntCampMonitor.getSalAcctId());
            aCMonitor.setActionType("Click");
            aCMonitor.setSourceAccntId(UserUtil.getUser().getId());
            AccntCampMonitor accntCampMon = accntCampMonitorMapper.queryByIdAc(aCMonitor);
            //查询会员id
            Account account = new Account();
            account.setId(aCMonitor.getAccntId());
            account = accountService.queryById(account);
            if (null == account) {
                accntCampMon.setFriendStatus("未注册");
            }
            alist.add(accntCampMon);
        }
        //排序
        Collections.sort(alist, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                AccntCampMonitor stu1 = (AccntCampMonitor) o1;
                AccntCampMonitor stu2 = (AccntCampMonitor) o2;
                return stu2.getLastUpdated().compareTo(stu1.getLastUpdated());
            }
        });
        result.put("rows",alist);
        return result;
    }

    /**
     * 分享领券活动-活动名额是否到达上限
     * @author  wangdawei
     * @param entity
     * @return
     * @throws Exception
     */
    public SaleActivity quotaLimit(SaleActivity entity) throws Exception {
        entity = this.shareCouponLoading(entity);
        //活动未过期，活动名额是否到达上限
        if (strN.equals(entity.getIsExpire())) {
            //活动参加活动人数
            AccntCampMonitor accntCampMonitor = new AccntCampMonitor();
            accntCampMonitor.setPageFlag(false);
            accntCampMonitor.setActionType("Collected");
            accntCampMonitor.setSalAcctId(entity.getId());
            accntCampMonitor.setSourceAccntId(entity.getSourceAccntId());
            List<AccntCampMonitor>  list = accntCampMonitorService.queryByExamplePage(accntCampMonitor);
            if (list.isEmpty() || list.size() <= entity.getParticipantLimit()) {
                entity.setUpperLimit("N");
            } else {
                //前端展示活动数量上限样式
                entity.setUpperLimit("Y");
                entity.setPromptp("活动名额已经达到上限");
            }
            entity.setSalCollectNum(list.size());
            return entity;
        } else {
            return entity;
        }
    }

    /**
     * 分享领券活动-判断客户是否已经领过券
     * @author  wangdawei
     * @param entity
     * @return
     * @throws Exception
     */
    public SaleActivity isReceiveCard(SaleActivity entity) throws Exception {
        entity = this.quotaLimit(entity);
        //判断客户是否已经领过券，'N'表示活动名额未达到上限
        if (strN.equals(entity.getUpperLimit())) {
            AccntCampMonitor accntCampMonitor = new AccntCampMonitor();
            accntCampMonitor.setPageFlag(false);
            accntCampMonitor.setAccntId(entity.getAccntId());
            accntCampMonitor.setSalAcctId(entity.getId());
            accntCampMonitor.setActionType("Collected");
            accntCampMonitor.setSourceAccntId(entity.getSourceAccntId());
            List<AccntCampMonitor>  list = accntCampMonitorService.queryByExamplePage(accntCampMonitor);
            if (list.isEmpty() || list.size() == 0) {
                //展示客户没有领取
                entity.setIsReceived("N");
            } else {
                //展示客户已经领取
                entity.setIsReceived("Y");
                entity.setPromptp("抱歉您已经参与过该活动");
            }
            return entity;
        } else {
            return entity;
        }
    }

    /**
     * 分享领券活动-创建领券记录
     * @author  wangdawei
     * @param entity
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = ServiceException.class)
    public SaleActivity createCollectRecord(SaleActivity entity) throws Exception {

        if (entity.getCouponsList().isEmpty()) {
            throw new ServiceException("SALEACTIVITY-009");
        }
        //插入领券记录
        List<Coupons> couponsList = entity.getCouponsList();
        for (Coupons coupons : couponsList) {
            Date d = new Date();
            CollectRecord collectRecord = new CollectRecord();
            String date = DateUtil.dateToStr(d,"yyyy-MM-dd HH:mm:ss");
            collectRecord.setCouponsId(coupons.getId());
            collectRecord.setClaimTime(date);
            collectRecord.setAccntId(entity.getAccntId());
            collectRecord.setClaimStatus("Received");
            collectRecord.setClaimantNum(1);
            collectRecord.setSourceAccntId(entity.getSourceAccntId());
            collectRecord.setSourceGuideId(entity.getSourceGuideId());
            collectRecord.setReceiveChannel(entity.getReceiveChannel());
            String  fixedDate = "FixedDate";
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            if (fixedDate.equals(coupons.getValidityOption())) {
                collectRecord.setEffectEndTime(coupons.getEffectEndTime());
                collectRecord.setEffectStaTime(coupons.getEffectStaTime());
            } else {
                collectRecord.setEffectStaTime(date);
                String endTime = df.format(new Date(d.getTime() + (long) coupons.getEffetDay() * 24 * 60 * 60 * 1000));
                collectRecord.setEffectEndTime(endTime);
            }
            if (StringUtils.isNotBlank(coupons.getCode())) {
                collectRecord.setWechatCode(coupons.getCode());
            }
            collectRecordService.insert(collectRecord);
        }
        return entity;
    }


    /**
     * 分享优惠券-入口
     * @author: wangdawei
     * @param entity
     */
    @Override
    public Map<String, Object> shareCoupons(SaleActivity entity) throws Exception {
        Map<String, Object> result = new HashMap<>(16);
        if (entity == null) {
            throw new ServiceException("SALEACTIVITY-010");
        }

        if (StringUtils.isBlank(entity.getOperatsScene())) {
            throw new ServiceException("SALEACTIVITY-011");
        }

        switch (entity.getOperatsScene()) {
            default:
                break;
            //场景1：用户加载活动页判断活动是否过期
            case ("pageLoadingPage"):
                entity = this.shareCouponLoading(entity);
                break;
            //场景2：用户点击按钮触发接口,判断日期
            case ("buttonTrigger"):
                entity = this.shareCouponLoading(entity);
                break;
            //场景3：用户进入该活动页面触发第一次逻辑判断&活动是否已经过期&活动名额是否到达上限&用户是否已经参加过该活动
            case ("compaignSharePage "):
                entity = this.isReceiveCard(entity);
                break;
            //场景4：用户是否已授权&活动是否已过期&活动名额是否已达到上限&优惠券的数量是否已达到上限
            case ("couponsReceivePage"):
                entity = this.isReceiveNum(entity);
                break;
        }
        result.put("newRow",entity);
        return result;
    }


    /**
     * 分享领券活动-判断优惠券领取数量是否已经达到上限
     * @author  wangdawei
     * @param entity
     * @return
     * @throws Exception
     */

    public SaleActivity isReceiveNum(SaleActivity entity) throws Exception {
        CoreUser user = UserUtil.getUser();
        entity.setAccntId(user.getId());
        entity = this.isReceiveCard(entity);
        //优惠券领取数量是否是达到上限,"N"表示客户未领取过
        if (strN.equals(entity.getIsReceived())) {
            Coupons coupons = new Coupons();
            coupons.setPageFlag(false);
            coupons.setIsEffect("Y");
            coupons.setCouponsClass("Coupon");
            coupons.setActivityId(entity.getId());
            List<Coupons>  coupList = couponsMapper.queryByExamplePage(coupons);
            List<Coupons>  cList = new ArrayList<>();
            for (Coupons coup : coupList) {
                CollectRecord collectRecord = new CollectRecord();
                collectRecord.setPageFlag(false);
                collectRecord.setCouponsId(coup.getId());
                List<CollectRecord> list = collectRecordService.queryByExamplePage(collectRecord);
                if (list.size() < coup.getCouponsNum()) {
                    cList.add(coup);
                }
            }
            if (cList.size() > 0) {
                //前端展示优惠券未领完样式
                entity.setCouponsNumLimit("N");
                //领券优惠券，创建领券记录
                entity.setCouponsList(cList);
                entity.setPromptp("领取成功");
                this.createCollectRecord(entity);
                //监控表插入数据
                this.createAccntCampMonitor(entity);

            } else {
                //前端展示优惠券已领完样式
                entity.setCouponsNumLimit("Y");
                entity.setPromptp("优惠券已经领完");
            }
            return entity;
        } else {
            return entity;
        }
    }

    /**
     * 分享领券活动-监控领券成功页面
     * @author  wangdawei
     * @param entity
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = ServiceException.class)
    public SaleActivity createAccntCampMonitor(SaleActivity entity) throws Exception {
    //客户领取玩优惠券，监控领券记录
        AccntCampMonitor accntCampMonitor = new AccntCampMonitor();
        accntCampMonitor.setAccntId(entity.getAccntId());
        accntCampMonitor.setSalAcctId(entity.getId());
        accntCampMonitor.setSourceAccntId(entity.getSourceAccntId());
        accntCampMonitor.setChannel("MiniProgram");
        accntCampMonitor.setPageTable("Share");
        accntCampMonitor.setSourceGuideId(entity.getSourceGuideId());
        accntCampMonitor.setActionType("Collected");
        accntCampMonitorService.insert(accntCampMonitor);
        return entity;
    }

    /**
     * 分享领券活动-被分享人页面的优惠卷统计问题，当前已参加活动名额
     * @author  wangdawei
     * @param entity
     * @return
     * @throws Exception
     */
    public SaleActivity getCount(SaleActivity entity) throws Exception {
        //活动参加活动人数
        AccntCampMonitor accntCampMonitor = new AccntCampMonitor();
        accntCampMonitor.setPageFlag(false);
        accntCampMonitor.setSalAcctId(entity.getId());
        accntCampMonitor.setActionType("Collected");
        accntCampMonitor.setSourceAccntId(entity.getSourceAccntId());
        List<AccntCampMonitor>  list = accntCampMonitorService.queryByExamplePage(accntCampMonitor);
        entity.setSalCollectNum(list.size());
        return entity;
    }

    /**
     * 使用优惠券-导购扫描消费者的券
     * @author  wangdawei
     * @param entity
     * @return
     * @throws Exception
     */
    @Override
    public SaleActivity createQrCode(SaleActivity entity) throws Exception {
        CoreUser user = UserUtil.getUser();
        String strJson = "";
        //二维码内容,跳转到优惠卷活动H5
        strJson = PropertyUtil.getProperty("couponGetDirectlyURL",
                user.getCorpid()) + "?id=" + entity.getId() + "&&corpid=" + user.getCorpid() + "&&source=" + "Store";
        //二维码存放位置,静态路径。
        String file = "/web/file/saleactivity/" + user.getCorpid() + "/";
        String fileName = entity.getId() + "_" + DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss") + ".png";
        //二维码的本地路径（默认Portal文件系统根目录）
        QRCodeUtil.tomakeMode(strJson, YmlConstants.getPortalShareFileDir() + file, fileName, 200, 200);
        entity.setCodeSavPath(YmlConstants.getPortalShareUrlDir() + file + fileName);
        entity.setCodeUrl(strJson);
        return entity;
    }

    /**
     * 生成大转盘H5页面，H5二维码图片
     * @author  wangdawei
     * @param entity
     * @return
     * @throws Exception
     */
    @Override
    public SaleActivity createH5UrlCode(SaleActivity entity) throws Exception {
        String strJson = "";
        //二维码内容,跳转到优惠卷活动H5
        if (null != entity.getSourceAccntId()) {
            strJson = PropertyUtil.getProperty("marketCampMobilePageURL", entity.getCorpid())
                    + "?id=" + entity.getId() + "&&corpid=" + entity.getCorpid()
                    + "&&sourceAccntId=" + entity.getSourceAccntId() + "&&source=" + "Store";
        } else {
            strJson = PropertyUtil.getProperty("marketCampMobilePageURL", entity.getCorpid())
                    + "?id=" + entity.getId() + "&&corpid=" + entity.getCorpid()
                    + "&&source=" + "Store";
        }
        //二维码存放位置,静态路径。
        String file = "/web/file/saleactivity/" + entity.getLoginCorpId() + "/";
        String fileName = entity.getId() + "_" + DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss") + ".png";
        //二维码的本地路径（默认Portal文件系统根目录）
        QRCodeUtil.tomakeMode(strJson, YmlConstants.getPortalShareFileDir() + file, fileName, 200, 200);
        entity.setCodeSavPath(YmlConstants.getPortalShareUrlDir() + file + fileName);
        entity.setCodeUrl(strJson);
        return entity;
    }

    /**
     * 查询所有在大屏的活动
     * @author KuangRuifeng
     * @date 2018/12/19
     * @param record 包含loginCorpId的查询信息
     * @return 大屏中展示的活动id数组
     * @throws Exception 异常
     */
    @Override
    public List<String> queryFilterIdList(SaleActivity record) throws Exception {
        List<String> result = new LinkedList<String>();
        // 先查询出当前账套下的所有需要过滤的活动id
        List<SaleActivity> saleActivityList = saleActivityMapper.queryFilterIdList(record);
        for (SaleActivity saleActivity : saleActivityList) {
            Long wheelCampId = saleActivity.getWheelCampId();
            Long shareCampId = saleActivity.getShareCampId();
            result.add(wheelCampId.toString());
            result.add(shareCampId.toString());
        }
        // 去重用的set
        Set<String> set = new HashSet<String>(result);
        result.clear();
        result.addAll(set);
        return result;
    }

    @Override
    public Map<String, Object> queryRedPackActivity(SaleActivity entity) throws Exception {
        Map<String, Object> map = new HashMap<>(4);
        // q渠道
        String receiveChannel = entity.getReceiveChannel();
        //新增浏览记录
        accntCampMonitorService.insertClickRecord(entity.getId(),receiveChannel,"View");

        Long acctId = UserUtil.getUser().getId();
        //检验数据
        Coupons coupons = checkRedPackData(entity,acctId);
        map.put("rows",coupons);
        return map;
    }

    /**
     * 红包活动校验：有效期，人数上限，金额上限，个数上限。
     * @author 路江
     * @param entity
     * @param acctId
     * @return
     * @throws Exception
     */
    @Override
    public Coupons checkRedPackData(SaleActivity entity,Long acctId) throws Exception {
        // 根据id查询活动信息
        entity = this.queryById(entity);
        if (entity == null) {
            // 如果活动不存在,认为是伪造请求
            CoreUser user = UserUtil.getUser();
            MpPayTools.processEntrance( user, MpPayConstants.FORGERY_REQUEST);
            throw new ServiceException("SALEACTIVITY-012");
        }

        Coupons coupons = new Coupons();
        coupons.setActivityId(entity.getId());
        List<Coupons> list = couponsMapper.queryByExamplePage(coupons);
        if (list == null || list.size() == 0) {
            throw new Exception("SALEACTIVITY-013");
        }
        // 获取红包活动对象
        coupons = list.get(0);
        coupons.setAttr1(entity.getActivityType());
        coupons.setAttr2(entity.getActivityClass());
        coupons.setAttr3(entity.getActivityState());

        // 活动开始、结束日期校验:红包尚未开抢，红包已经过期
        if (StringUtils.isBlank(coupons.getEffectStaTime()) || StringUtils.isBlank(coupons.getEffectEndTime())) {
            throw new Exception("SALEACTIVITY-014");
        }
        // 判断活动所处状态，未开始，已结束，进行中
        //当前时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // 活动开始时间
        Long begin = (Long)((format.parse(coupons.getEffectStaTime()).getTime()
                - format.parse("1970-01-01").getTime()) / 1000);
        // 活动结束时间
        Long end = (Long)((format.parse(coupons.getEffectEndTime()).getTime()
                - format.parse("1970-01-01").getTime()) / 1000);

        Long nowDate = (Long)((new Date()).getTime()
                - format.parse("1970-01-01").getTime()) / 1000;
        if (nowDate < begin) {
            throw new ServiceException("SALEACTIVITY-015");
        }
        if (nowDate > end) {
            throw new ServiceException("SALEACTIVITY-016");
        }

        // 判断每人领取数量是否达到上限
        CollectRecord collectRecord = new CollectRecord();
        collectRecord.setCouponsId(coupons.getId());
        collectRecord.setAccntId(acctId);
        collectRecord.setPageFlag(false);

        List<CollectRecord> recordList = collectRecordService.queryByExamplePage(collectRecord);
        if (recordList.size() == coupons.getLimitGet()) {
            throw new ServiceException("SALEACTIVITY-017");
        }

        // 判断红包总领取数量是否已经到达上限
        collectRecord = new CollectRecord();
        collectRecord.setCouponsId(coupons.getId());
        collectRecord.setPageFlag(false);
        List<CollectRecord> collectRecords = collectRecordService.queryByExamplePage(collectRecord);
        if (collectRecords.size() == coupons.getCouponsNum()) {
            throw new ServiceException("SALEACTIVITY-018");
        }
        // 统计发出去的总金额
        Double amountTotal = 0.0;
        for (CollectRecord collectRecord1 : collectRecords) {
            amountTotal += collectRecord1.getAmount();
        }
        coupons.setTotalAmount(amountTotal);
        // 获取当前红包活动总金额
        Double maxTotalAmoun = 0.0;
        if (null != coupons.getMaxTotalAmount()) {
            maxTotalAmoun = coupons.getMaxTotalAmount();
        }
        // 如果已领取总金额大于等于活动总金额,则表示全部领取完成
        if (amountTotal >= maxTotalAmoun) {
            throw new ServiceException("SALEACTIVITY-019");
        }

        // 验证发放及领取数量
        // 发放总数量
        Integer couponsNum = coupons.getCouponsNum();
        // 如果未维护值,则默认为0,确保不会被领取
        if (Objects.isNull(couponsNum)) {
            couponsNum = 0;
        }
        // 已领取数量
        Integer receivedNum = coupons.getReceivedNum();
        // 空默认为0
        if (Objects.isNull(receivedNum)) {
            receivedNum = 0;
        }
        if (receivedNum >= couponsNum) {
            throw new ServiceException("SALEACTIVITY-019");
        }
        return coupons;
    }

    @Override
    public Double getRedPackAmount(Coupons entity) throws Exception {
        Double winningOdds = entity.getWinningOdds();
        Double amount = 0.0;
        //判断是否中奖
        boolean win = false;
        if (winningOdds == 100.0) {
            win = true;
        } else if (winningOdds == 0.0) {
            win = false;
        } else  {
            double random = Math.random() * 100;
            if (winningOdds >= random) {
                win = true;
            }
        }
        //中奖情况
        if (win) {
            // 随机金额
            String randomAmount = "RandomAmount";
            // 固定金额
            String fixedAmount = "FixedAmount";
            // 指定金额
            String specifiedAmount = "SpecifiedAmount";
            if (StringUtils.equals(entity.getCouponsType(),randomAmount)) {
                //返回指定范围的随机数(m-n之间) Math.random()*(n+1-m)+m
                amount = Math.random() * (entity.getMaxRandomAmount() - entity.getMinRandomAmount()) + entity.getMinRandomAmount();
            } else if (StringUtils.equals(entity.getCouponsType(),fixedAmount)) {
                amount = entity.getDisAmount();
            } else if (StringUtils.equals(entity.getCouponsType(),specifiedAmount)) {
                //解析指定金额 根据逗号隔开，随机去其中一个金额
                String[] arr = entity.getDesignatedAmount().split(",");
                int index = (int) (Math.random() * arr.length);
                amount = Double.valueOf(arr[index]);
            }
        }
        return amount;
    }
}

